package com.example.websocket.another.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.websocket.another.entity.UserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * jwt工具类
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017/9/21 22:21
 */
@Slf4j
public class JwtUtil {

    private static String secret = "f4e2e52034348f86b67cde581c0f9eb5";
    private static long expire = 604800;
    public final static String header = "token";

    public static String validateToken(String token) throws Exception {
        if (token == null || token.isEmpty()) {
            throw new Exception("JWT：token为空！" + token);
        }
        Claims claims = getClaimByToken(token);
        if (claims == null || isTokenExpired(claims.getExpiration())) {
            throw new Exception("JWT：token无效！" + token);
        }
        return claims.getSubject();
    }

    /**
     * 生成jwt token
     */
    private static String generateToken(String subject) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(subject)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 根据实体类构造 返回token
     *
     * @param userEntity
     * @return
     */
    public static String generateToken(UserEntity userEntity) {
        JSONObject user = new JSONObject();
        user.put("id", userEntity.getId());
        user.put("username", userEntity.getUserName());
        user.put("userSex", userEntity.getUserSex());
        return generateToken(user.toJSONString());
    }

    /**
     * 根据token 返回实体信息
     *
     * @param token
     * @return
     */
    public static UserEntity validateTokenGetUser(String token) {
        String sub;
        try {
            sub = validateToken(token);
        } catch (Exception e) {
            log.error("token 验证失效");
            return null;
        }
        UserEntity user = JSONObject.parseObject(sub, UserEntity.class);
//        UserEntity entity = new UserEntity();
//        entity.setId(user.getLong("id"));
//        entity.setUserName(user.getString("username"));
//        entity.setUserSex(user.getObject("userSex", UserSexEnum.class));
        return user;
    }

    public static Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

}
